<template>
	<view>
		<view class="top-tab">
			<view class="top-tab-cell" :class="{active: status == 0 }" @click="changeStatus(0)">全部</view>
			<view class="top-tab-cell" :class="{active: status == 1 }" @click="changeStatus(1)">问诊中</view>
			<view class="top-tab-cell" :class="{active: status == 2 }" @click="changeStatus(2)">待支付</view>
			<view class="top-tab-cell" :class="{active: status == 3 }" @click="changeStatus(3)">退款中</view>
			<view class="top-tab-cell" :class="{active: status == 4 }" @click="changeStatus(4)">已退款</view>
			<view class="top-tab-cell" :class="{active: status == 5 }" @click="changeStatus(5)">待评价</view>
			<view class="top-tab-cell" :class="{active: status == 6 }" @click="changeStatus(6)">已完成</view>
		</view>
		<view class="list" style="text-align: center;background-color: #F6FAFA;padding-top: 120rpx;">
			<view v-for="(item,index) in wordDataList" :key="index" class="order-card" @tap.stop="joinChat(item)">
				<view
					style="width: calc( 100% - 40rpx );display: flex;align-items: center;justify-content: space-between;padding-top: 20rpx;margin-bottom: 20rpx;">
					<view style="display: flex;align-items: center;">
						<image
							:src="item.type.indexOf('图文')>-1?'../../static/images/tuwen.png':'../../static/images/shipi.png'"
							style="width: 42rpx;margin-right: 10rpx;" mode="widthFix"></image>
						<text style="margin-right: 10rpx;font-size: 30rpx;font-weight: bold;">{{item.type}}</text>
						<image class="arrow"
							src="http://tuozhen1.oss-cn-beijing.aliyuncs.com/ueditor/upload/weixin/images/arrow.png">
						</image>
					</view>
					<view style="display: flex;align-items: center;">
						<view style="padding-right: 20rpx;border-right: 2rpx solid #EFEFEF;color: #999999;">
							{{changeDateFormat(item.time)}}</view>
						<view style="padding-left: 20rpx;">{{ renderedStatus(item) }}</view>
					</view>
				</view>
				<view
					style="width: calc( 100% - 40rpx );border-top: 2rpx solid #EFEFEF;padding-top: 20rpx;margin-bottom: 30rpx;">
					<view style="text-align: left;">
						<text>主诉：</text>
						<text>{{item.problem}}</text>
					</view>
					<view
						style="width: calc( 100% - 40rpx );display: flex;align-items: center;margin-top: 20rpx;overflow: hidden;white-space: nowrap;text-overflow: ellipsis;">
						<image class="haed mr25" :src="item.docPhoto" style="margin-right: 20rpx;"></image>
						<text class="bold mr25">{{item.docName}}</text>
						<text class="mr25">{{item.deptName}}</text>
						<text
							style="width: 300rpx;overflow: hidden;white-space: nowrap;text-overflow: ellipsis;">{{item.hspName}}</text>
					</view>
				</view>
				<view class="order-footer">
					<view style="font-size: 30rpx;font-weight: bold;">
						价格￥{{item.price}}
					</view>
					<view class="order-btn" @tap.stop="backout(item.orderId,item.price)"
						v-if="item.ordPayStatus==1 && item.ordStatus==1&&item.price>0&&item.recipeId==-3">
						撤销挂号
					</view>
					<view class="order-btn" @tap.stop="confirmDialog(item.medDocInfoId,item.problem,item.id)"
						v-if="item.ordStatus == 3">
						去评价
					</view>

					<view class="order-btn" @click.stop="toPay(item)"
						v-if="item.ordPayStatus == 0 && item.ordStatus==0">
						去支付
					</view>
				</view>
			</view>
		</view>
		<uni-load-more :status="message" :contentText="contentText" @clickLoadMore="loadMore"></uni-load-more>

		<uni-popup ref="dialogInput" type="dialog" @change="change">
			<view>
				<uni-rate :value="number" @change="onChange" />
			</view>
			<uni-popup-dialog class="uni-popup-dialog" mode="input" placeholder="请输入评价内容"
				@confirm="dialogInputConfirm"></uni-popup-dialog>
		</uni-popup>
		<view style="position: fixed;bottom: 60rpx;right: 50rpx;
			width: 120rpx;height: 120rpx;background: #BE965B;
			box-shadow: 0px 0px 22rpx 2rpx #BE965B;border-radius: 50%;
			display: flex;flex-direction: column;align-items: center;justify-content: center;z-index: 999;" @click="tohome">
			<image src="../../static/images/sy@2x.png" style="width: 50%;" mode="widthFix"></image>
			<view style="color: #FFFFFF;">首页</view>
		</view>
		<view style="text-align: center;font-size: 10px;" v-if="statusOne">由重庆拓诊信息技术有限公司提供技术支持</view>
		<wyb-popup ref="popup" type="bottom" height="100" width="500" radius="2" :showCloseIcon="true">
			<view class="popup-content">
				<view class="part1">选择支付平台</view>
				<!-- 暂时 -->
				<!-- <view class="part2" @click="pay1">
					<image src="@/static/images/medical-logo.png" mode="" style="margin-left: 20rpx;"></image>
					<view class="" style="margin-left: 30rpx;">医保支付</view>
				</view> -->

				<view class="part3" @click="pay">
					<image src="@/static/images/wxzf.png" mode="" style="margin-left: 20rpx;"></image>
					<view class="" style="margin-left: 30rpx;">微信支付</view>
				</view>
			</view>
		</wyb-popup>
	</view>
</template>

<script>
	import wybPopup from '@/components/wyb-popup/wyb-popup.vue'
	import uniPopupShare from '@/components/uni-popup/uni-popup-share.vue'
	import uniRate from '@/components/uni-rate/uni-rate.vue'
	const WxAuth = require('@/utils/wxlogin');
	export default {
		components: {
			statusOne: false,
			uniPopupShare,
			uniRate
		},
		data() {
			return {
				openid: '',
				number: 5,
				wx: "https://app.mzmzb.com", //https://app.mzmzb.com   http://localhost:6110
				hasNextPage: true, //是否有下一页
				message: 'more',
				contentText: {
					contentdown: "点击显示更多",
					contentrefresh: "正在加载...",
					contentnomore: "没有更多数据了"
				},
				tab: 2,
				pageIndex: 1,
				freeDataList: [], //公益咨询列表
				wordDataList: [], //图文咨询列表
				videoDataList: [], //视频咨询列
				usrUserId: null,
				value: '', //评价内容
				docId: null,
				problems: '',
				userId: null,
				ispay: null,
				status: 0,
				current: 1,
				payitem: {}
			};
		},
		onLoad(option) {
			this.ispay = option.ispay
			//初始化数据
			this.usrUserId = option.userId;
			// this.usrUserId = 5557
			this.userId = option.userId;

			//图文咨询撤销咨询后跳转
			if (typeof option.tab != 'undefined') {
				this.tab = option.tab;
			}

		},
		onShow() {
			let code = uni.getStorageSync('code')
			this.getOpenIdByHspId(code)
			this.openid = uni.getStorageSync('openId')
			console.log(this.openid)
			this.wordData(this.usrUserId);
		},
		onUnload() {
			if (this.ispay == '1') {
				const pages = getCurrentPages();
				const beforePage = pages[pages.length - 2]
				beforePage.setData({ //会直接更新A页面的数据，A页面不需要其他操作
					isNotShow: "1"
				})
			}
		},
		onReachBottom() {
			this.statusOne = true
		},
		methods: {
			getOpenIdByHspId(code) {
				uni.request({
					url: this.wx + '/application-usrapp/wx/getOpenIdByHspId.tz',
					method: 'get',
					data: {
						code: code,
						userId: this.usrUserId,
						hspId: this.hspId
					},
					success: (res) => {
						uni.setStorageSync('openid', res.data.errMsg)
					}
				})
			},
			changeStatus(val) {
				this.status = val
				this.current = 1
				this.wordData(this.usrUserId);
			},
			renderedStatus(obj) {
				if (obj.ordPayStatus == 1 && obj.ordStatus == 1) {
					return '问诊中'
				} else if (obj.ordPayStatus == 0 && obj.ordStatus == 0) {
					return '待支付'
				} else if (obj.ordPayStatus == 4 || obj.ordPayStatus == 5) {
					return '咨询退款中'
				} else if (obj.ordPayStatus == 6) {
					return '咨询已退款'
				} else if (obj.ordStatus == 3) {
					return '待评价'
				} else if (obj.ordStatus == 6 || obj.ordStatus == 5) {
					return '已完成'
				}
			},
			// renderedStatus(obj){
			// 	if(obj.ordPayStatus==1 && obj.ordStatus==1){
			// 		return '问诊中'
			// 	}else if(obj.ordPayStatus == 0 && obj.ordStatus==0){
			// 		return '待支付'
			// 	}else if(obj.recipePayStatus == 0){
			// 		return '处方未支付'
			// 	}else if(obj.ordPayStatus ==4 || obj.ordPayStatus == 5 ){
			// 		return '咨询退款中'
			// 	}else if(obj.recipePayStatus == 3 ){
			// 		return '处方退款中'
			// 	}else if(obj.ordPayStatus == 6  ){
			// 		return '咨询已退款'
			// 	}else if(obj.recipePayStatus == 4  ){
			// 		return '处方已退款'
			// 	}else if(obj.ordStatus == 3  ){
			// 		return '待评价'
			// 	}else if(obj.ordStatus == 6 || obj.ordStatus == 5){
			// 		return '已完成'
			// 	}
			// },
			tohome() {
				uni.reLaunch({
					url: '/pages/index/index'
				})
			},
			onChange(e) {
				console.log(e.value)
				console.log("e:" + JSON.stringify(e))
				this.number = e.value
			},
			change(e) {
				console.log('popup ' + e.type + ' 状态', e.show)
			},
			confirmDialog(medDocInfoId, problem, orderId) {
				this.docId = medDocInfoId
				this.problems = problem
				this.orderId = orderId
				this.$refs.dialogInput.open()
			},
			dialogInputConfirm(done, val) {
				var that = this;
				that.value = val
				let data = {
					content: that.value,
					docInfoId: that.docId,
					score: that.number,
					disease: that.problems,
					orderId: that.orderId,
					usrUserId: that.usrUserId
				}
				that.func.$request('userOrd/evaluateDoctor.tz?content=' + that.value + '&docInfoId=' +
					that.docId + '&score=' + that.number + '&disease=' + that.problems + '&orderId=' + that.orderId +
					'&usrUserId=' +
					that.usrUserId, {}, 'POST', 'application/j  son', 'APP_USER_AND').then(res => {
					console.log(res.data);
					if (res.data.result == true) {
						that.wordData(that.usrUserId);
						// that.videoData(that.usrUserId);
					}
				})
				done()

			},
			toPay(item) {
				this.$refs.popup.show()
				this.payitem = item
			},
			// 微信支付
			pay() {
				var that = this
				var price = this.payitem.price;
				var orderId = this.payitem.orderId;
				let openId = uni.getStorageSync('openId')
				let code = uni.getStorageSync('code')
				uni.login({
					success: function(loginRes) {
						// that.func.$request('wx/messegPay.tz?money=' + price + '&orderId=' +
						// 	orderId + '&code=' + code + '&hspId=23840', {}, 'POST',
						// 	'application/x-www-form-urlencoded').then(item => {
							that.func.$request('wx/messegPay.tz?money=' +
									price + '&orderId=' +
									orderId +
									'&hspId=23840'
									+ '&code=' + loginRes.code,{},'POST','application/x-www-form-urlencoded').then(item=>{
							if (item.data.success) {
								var timestamp = item.data.result.timeStamp;
								var nonceStr = item.data.result.nonceStr;
								var packages = 'prepay_id=' + item.data.result.prepayid;
								var paySign = item.data.result.sign;
								uni.requestPayment({
									timeStamp: timestamp,
									nonceStr: nonceStr,
									package: packages,
									signType: 'MD5',
									paySign: paySign,
									success: function(res) {
										that.sendMsg(orderId)
										that.joinChat(orderId)
									},
									fail: function(err) {
										console.log('fail:' +JSON.stringify(err));
									}
								});
							} else {
								that.isSaveing = false
								that.warnMessage = item.data.errMsg;
								that.warnTime = 3000;
								that.$refs.popup.open();
							}
						}).catch(error => {
							that.isSaveing = false
							that.warnMessage = '支付失败';
							that.warnType = 'error';
							that.$refs.popup.open();
						})
					}
				});
			},
			// 医保支付
			pay1() {
				this.$refs.popup.close()
				var that = this;
				let aimkey = null
				var price = this.payitem.price;
				var orderId = this.payitem.orderId;
				let openId = uni.getStorageSync('openId')
				let data = {
					hspId: that.hspId,
					orderId: orderId,
					openId: openId,
				}
				that.func.$request('rczyywx/registerSettlement.tz', data, 'POST', 'application/x-www-form-urlencoded')
					.then(res => {
						wx.navigateToMiniProgram({
							appId: 'wx25ec5e985ebaacc7',
							path: 'pages/nativeLoading/index?webUrl=' + encodeURIComponent(res.data
								.errMsg),
							envVersion: 'trial'
						})
					})
			},




			//加载更多
			loadMore(e) {
				if (e.detail.status == 'more') {
					var that = this;
					that.message = 'loading';
					this.current++
					// that.pageIndex = that.pageIndex + 1;
					setTimeout(() => {
						this.wordData(this.usrUserId);
						// if (that.hasNextPage) {
						// 	that.message = 'more';
						// } else {
						// 	that.message = 'noMore';
						// }
					}, 500);
				}
			},
			chosetab(e) {
				this.tab = e;
				this.videoData(this.userId);
			},
			//加入聊天
			joinChat(item) {
				console.log('====================joinChat1')
				if ((item.ordPayStatus == 1 && item.ordStatus == 1) || (item.ordStatus == 6 || item.ordStatus == 5)) {
					var that = this;
					var messageType = '';
					var userNickname = '';
					let type = item.type.indexOf('图文') > -1 ? '1' : '2'
					if (type == '1') {
						messageType = '图文订单';
						userNickname = item.nickName;
					} else {
						messageType = '视频订单';
						userNickname = item.uname;
					}

					if (!item.id || !item.docUserId || !item.docPhoto || !item.docName || !item.usrPhoto || !item
						.nickName) {
						return;
					}
					console.log('====================joinChat3')
					var orderExt = {}; //发消息所需要的拓展数据
					orderExt.orderId = item.id;
					orderExt.messageType = messageType;
					orderExt.doctorId = item.docUserId;
					orderExt.doctorHead = item.docPhoto;
					orderExt.doctorNickname = item.docName;
					orderExt.userId = this.usrUserId;
					orderExt.userHead = item.usrPhoto;
					orderExt.userNickname = item.nickName;
					orderExt.ordStatus = item.ordStatus
					uni.navigateTo({
						url: '/pages/chatroom/chatroom?username=' + JSON.stringify(orderExt)
					});
				}
			},
			freeData(userId) {
				let openid = uni.getStorageSync('openid')
				var usrUserId = userId; //用户id
				var hosId = this.hspId; //永川医院id
				var current = 1; //当前页数
				let data = {
					usrUserId: usrUserId,
					hosId: hosId,
					current: current
				}
				this.func.$request('userOrd/getFree_dl.tz', data, 'GET').then(res => {
					if (res.data.success) {
						this.freeDataList = res.data.result.list;
					}
				})
			},
			wordData(userId) {

				var that = this;
				var hosId = this.hspId; //永川医院id
				let openid = uni.getStorageSync('openId')
				let data = {
					status: this.status,
					userId: userId,
					current: this.current
				}
				this.func.$request('newsInquiry/queryUserInquiryList.tz', data, 'GET').then(res => {
					if (res.data.success) {
						that.hasNextPage = res.data.result.hasNextPage;
						if (that.hasNextPage) {
							that.message = 'more';
						} else {
							that.message = 'noMore';
						}
						if (this.wordDataList.length > 0 && this.current != 1) {
							let list = JSON.parse(JSON.stringify(res.data.result.list))
							this.wordDataList.push(...list)
						} else {
							this.wordDataList = JSON.parse(JSON.stringify(res.data.result.list));
						}
						// that.wordDataList = res.data.result.list;
					}
				})
			},
			videoData(userId, type) {
				var that = this;
				var usrUserId = userId; //用户id
				var hosId = this.hspId; //永川医院id
				var current = 1; //当前页数
				let data = {
					usrUserId: usrUserId,
					hosId: hosId,
					current: current
				}
				this.func.$request('wx/WXGetVideo.tz', data, 'GET').then(res => {
					if (res.data.success) {
						that.hasNextPage = res.data.result.hasNextPage;
						if (that.hasNextPage) {
							that.message = 'more';
						} else {
							that.message = 'noMore';
						}
						that.videoDataList = res.data.result.list;
					}
				})

			},
			//格式化时间
			changeDateFormat(cellval) {
				var dateVal = cellval + "";
				if (cellval != null) {
					var date = new Date(parseInt(dateVal.replace("/Date(", "").replace(")/", ""), 10));
					var month = date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1;
					var currentDate = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
					var hours = date.getHours() < 10 ? "0" + date.getHours() : date.getHours();
					var minutes = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes();
					var seconds = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
					// return date.getFullYear() + "-" + month + "-" + currentDate + " " + hours + ":" + minutes + ":" + seconds;
					return month + "/" + currentDate + " " + hours + ":" + minutes + ":" + seconds;
				}

			},
			//撤销咨询
			backout(id, price) {
				uni.navigateTo({
					url: '/pages/backout/index?medicalNum=' + id + '&price=' + price
				});
			},
			//付费咨询
			doctorNavigateTo(doctorId) {
				var usrUserId = uni.getStorageSync("usrUserId");
				uni.navigateTo({
					url: '/pages4/doctor/index?docId=' + doctorId + '&usrUserId=' + usrUserId
				});
			},
			//加载更多请求数据的方法
			requestData(tab, pageIndex) {
				var that = this;
				var url = '';
				if (tab == 1) {
					url = 'https://app.mzmzb.com/application-usrapp/userOrd/getFree_dl.tz';
				} else if (tab == 2) {
					url = 'https://app.mzmzb.com/application-usrapp/wx/WXGetWords.tz';
				} else {
					url = 'https://app.mzmzb.com/application-usrapp/wx/WXGetVideo.tz';
				}
				var usrUserId = that.usrUserId; //用户id
				var hosId = this.hspId; //永川医院id
				let data = {
					usrUserId: usrUserId,
					hosId: hosId,
					current: pageIndex
				}
				this.func.$request(url, data, 'GET').then(res => {
					if (res.data.success) {
						that.hasNextPage = res.data.result.hasNextPage;
						if (that.hasNextPage) {
							that.message = 'more';
						} else {
							that.message = 'noMore';
						}
						var dataList = res.data.result.list;
						if (dataList.length > 0) {
							dataList.forEach(function(item, index) {
								if (tab == 1) {
									that.freeDataList.push(item);
								} else if (tab == 2) {
									that.wordDataList.push(item);
								} else {
									that.videoDataList.push(item);
								}
							});
						}
					} else {
						that.message = 'noMore';
					}
				}).catch(error => {
					that.message = 'noMore';
				})

			}
		}
	};
</script>

<style lang="less">
	.top-tab {
		width: 100%;
		display: flex;
		align-items: center;
		background-color: #FFFFFF;
		position: fixed;
		top: 0rpx;
		left: 0rpx;
		z-index: 999;

		.top-tab-cell {
			width: 14%;
			text-align: center;
			height: 100rpx;
			line-height: 100rpx;
			box-sizing: border-box;
		}

		.active {
			color: #00BAAD;
			border-bottom: 2rpx solid #00BAAD;
		}
	}

	.list {
		.order-card {
			border: 2rpx solid #F2F9F9;
			box-shadow: 0px 2rpx 17rpx 2rpx rgba(162, 215, 211, 0.16);
			border-radius: 32rpx;
			background-color: #FFFFFF;
			margin-top: 20rpx;
			padding-left: 40rpx;
			width: 90%;
			margin: 20rpx auto 20rpx auto;

			.order-footer {
				width: calc(100% - 40rpx);
				border-top: 2rpx solid #EFEFEF;
				display: flex;
				align-items: center;
				justify-content: space-between;
				padding-top: 20rpx;
				padding-bottom: 20rpx;

				.order-btn {
					width: 174rpx;
					height: 64rpx;
					line-height: 64rpx;
					background: #FFFFFF;
					border: 2rpx solid #FE9539;
					border-radius: 30rpx;
					color: #FE9539;
				}
			}
		}

		.text {
			line-height: 45rpx;
		}

		.haed {
			width: 65rpx;
			height: 65rpx;
			border-radius: 50%;
		}

		.now {
			display: inline-block;
			width: 245rpx;
			line-height: 50rpx;
			border-radius: 10rpx;
			border: 1rpx solid #EFEFEF;
			text-align: center;
		}
	}

	page {
		background: #EFEFEF;

		.uni-popup-dialog {
			padding-top: 50rpx;
			margin-top: -70rpx;
		}

	}

	.part1 {
		height: 80rpx;
		text-align: center;
		line-height: 80rpx;
	}

	.imgs {
		display: flex;

		image {
			width: 120rpx;
			height: 97rpx;
			margin: 10rpx;
		}
	}

	.part2 {
		height: 100rpx;
		width: 96%;
		margin: 0 auto;
		border-bottom: 2rpx solid #ECECEC;
		display: flex;
		align-items: center;

		image {
			width: 70rpx;
			height: 30rpx;
		}
	}

	.part3 {
		height: 64rpx;
		width: 96%;
		margin: 0 auto;
		display: flex;
		align-items: center;
		border-bottom: 2rpx solid #ECECEC;

		image {
			width: 77rpx;
			height: 64rpx;
		}
	}
</style>